﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocket4Net;

namespace WpfAppWebSocket1
{
    internal class WebSocketClient2
    {
        WebSocket websocket = null;

        private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //接收服务端发来的消息
            MessageReceivedEventArgs responseMsg = (MessageReceivedEventArgs)e;
            string strMsg = responseMsg.Message;
            if (strMsg.Equals("broadcast"))
            {
                //websocketToPlay();
            }
            else if (strMsg.Equals("broadcastStop"))
            {
                //websocketToStop(sender, e);
            }
        }

        private void websocket_Closed(object sender, EventArgs e)
        {
            DisplayStatusInfo("websocket connect failed!");
        }

        private void websocket_Opened(object sender, EventArgs e)
        {
            DisplayStatusInfo("websocket connect success!");
        }

        //websocket连接
        public void connectWebsocket()
        {
            websocket = new WebSocket("ws://localhost:8080/FrameServlet/websocket/broadcast");
            websocket.Opened += websocket_Opened;
            websocket.Closed += websocket_Closed;
            websocket.MessageReceived += websocket_MessageReceived;
            websocket.Open();
        }
        private delegate void DoLog(string msg);
        private void DisplayStatusInfo(string msg)
        {
            //if (this.InvokeRequired)
            //{
            //    DoLog doLog = new DoLog(DisplayStatusInfo);
            //    this.Invoke(doLog, new object[] { msg });
            //}
            //else
            //{
            //    if (msg.Trim().Length > 0)
            //    {
            //        ListBoxStatus.Items.Insert(0, msg);
            //        if (ListBoxStatus.Items.Count > 100)
            //        {
            //            ListBoxStatus.Items.RemoveAt(ListBoxStatus.Items.Count - 1);
            //        }
            //    }
            //}
        }
    }
}
